﻿using AutoMapper;
using DDD.Application;
using DDD.EFCore;
using GoodsModule.Domain.GoodsAggregate;
using GoodsModule.Domain.GoodsCategoryAggregate;
using GoodsModule.Infrastructure.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GoodsModule.Application.Commands
{
    [AutoMapperTo(typeof(Domain.GoodsCategoryAggregate.GoodsCategory))]
    public class CreateGoodsCategoryCommannd : ICommand<Domain.GoodsCategoryAggregate.GoodsCategory>
    {
        [Comment("标题")]
        [Required]
        [StringLength(20)]
        public string Title { get; set; } = string.Empty;

        [Comment("排序")]
        [Required]
        public int Sort { get; set; } = 1000;
    }

    public class CreateGoodsCategoryCommanndHandler(IMapper mapper, GoodsCategoryRepository repository, ILogger<CreateGoodsCategoryCommanndHandler> logger) 
        : ICommandHandler<CreateGoodsCategoryCommannd, Domain.GoodsCategoryAggregate.GoodsCategory>
    {
        public async Task<GoodsCategory> Handle(CreateGoodsCategoryCommannd request, CancellationToken cancellationToken)
        {
            var goodsCategory = mapper.Map<GoodsCategory>(request);
            goodsCategory = await repository.AddAsync(goodsCategory);
            //TODO: SaveUnitOfWorkAsync还得处理下
            //await repository.UnitOfWork.SaveUnitOfWorkAsync();
            logger.LogInformation("CreateGoodsCategoryCommanndHandler GoodsCategory {}", goodsCategory.Id);
            return goodsCategory;
        }
    }
}
